// 身份证号码校验函数（支持18位）
export const validateIdCard = (idCard) =>  {
  // 基本格式校验（18位）
  const pattern = /^[1-9]\d{5}(18|19|20|21)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  if (!pattern.test(idCard)) return false

  // 校验出生日期是否合法
  const birthDateStr = idCard.slice(6, 14)
  const year = +birthDateStr.slice(0, 4)
  const month = +birthDateStr.slice(4, 6)
  const day = +birthDateStr.slice(6, 8)
  const birthDate = new Date(year, month - 1, day)
  if (
    birthDate.getFullYear() !== year ||
    birthDate.getMonth() + 1 !== month ||
    birthDate.getDate() !== day
  ) {
    return false
  }

  // 校验最后一位校验码
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  const sum = idCard
    .slice(0, 17)
    .split('')
    .reduce((total, num, index) => total + parseInt(num) * weights[index], 0)
  const lastChar = idCard[17].toUpperCase()

  return checkCodes[sum % 11] === lastChar
}
